/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Action;

import Entity.Account;
import Entity.Customer;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Cyrax
 */
@Stateless
public class AccountSessionBean implements AccountSessionBeanLocal {

    @PersistenceContext(unitName = "EasyTickets-ejbPU")
    private EntityManager em;

    public void persist(Object object) {
        em.persist(object);
    }

    @Override
    public void insertAccount(Account ac)
    {
        try {
             em.persist(ac);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    @Override
    public List<Account> listAllAccount() {
        List<Account> ac = null;
        ac = em.createNamedQuery("Account.findAll").getResultList();
        return ac;

    }

    @Override
    public void deleteAccount(Account ac) {
        if (ac != null) {
            em.remove(em.merge(ac));
        } else {
            System.out.println("Not found account to delete");
        }
    }

    @Override
    public void updateAccount(String accountId, String accName,double amount, String email) {
        Account ac = em.find(Account.class, accountId);
        Customer cu = em.find(Customer.class, email);
        if (ac != null) {

            ac.setAccountName(accName);
            ac.setAmount(amount);
            ac.setCustomer(cu);

            em.persist(ac);
        } else {
            System.out.println("Not found ID to Update");
        }

    }

    @Override
    public List<Account> searchAccount(String accId) {
        List<Account> ac = null;

        ac = em.createQuery("SELECT a FROM Account a WHERE a.accountId like :accountId").setParameter("accountId", "%" + accId + "%").getResultList();
        System.out.println("accountId : " + accId);


        return ac;
    }
    boolean result = false;

    @Override
    public boolean checkAccountId(String accId) {
        List<Account> adList = null;
        adList = em.createQuery("SELECT a FROM Account a").getResultList();
        for (Account ad : adList) {
            if (ad.getAccountId().equals(accId)) {
                result = true;
                break;
            } else {
                result = false;
            }
        }
        return result;
    }

    @Override
    public Account getAccountByEmail(String email){
        return (Account) em.createQuery("SELECT a FROM Account WHERE a.email = :email").setParameter(email, email).getSingleResult();
    }
}
